package com.xiaoy.github.proxy.dynamic_proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author liuyongtao
 * @since 2021-3-15 14:01
 */
public class DynamicProxyHandler<T> implements InvocationHandler {

    private T obj;

    public DynamicProxyHandler(T obj) {
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(obj.getClass().getName() + " 执行之前。。。");
        Object invoke = method.invoke(obj, args);
        System.out.println(obj.getClass().getName() + " 执行之后。。。");
        return invoke;
    }

    /**
     * 获取代码对象
     *
     * @return {@link T}
     * @author liuyongtao
     * @since 2021-3-15 14:16
     */
    public T proxy() {
        return (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
    }
}
